package com.bosssoft.cloud.wechat.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bosssoft.cloud.app.domain.AppCheckRecord;
import com.bosssoft.cloud.config.domain.PageVO;
import com.bosssoft.cloud.wechat.common.bean.PageInfo;
import com.bosssoft.cloud.wechat.common.bean.ckrecord.CkRcdCondParam;
import com.bosssoft.cloud.wechat.common.bean.einvoice.EinvoiceDTO;
import com.bosssoft.cloud.wechat.common.service.AppCheckRecordService;
import com.bosssoft.cloud.wechat.infrastructure.util.IDUtil;
import com.bosssoft.cloud.wechat.infrastructure.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author wcy create on 2021/5/14 16:09 下午
 */
@Slf4j
@Service
public class AppCheckRecordServiceImpl implements AppCheckRecordService {

    @Autowired
    private com.bosssoft.cloud.app.service.AppCheckRecordService appCheckRecordService;

    @Override
    public Boolean notSave(AppCheckRecord record) {
        return appCheckRecordService.selectByUserIdAndElements(
                record.getUserId(),
                record.getEInvoiceCode(),
                record.getEInvoiceNumber(),
                record.getRandomNumber()
        ).isEmpty();
    }

    @Override
    public PageVO<?> pageByOpenidAndKeyword(CkRcdCondParam param, PageInfo pageInfo) {
        return appCheckRecordService.selectByUserIdAndSearch(
                param.getUserId(),
                param.getKeyword(),
                pageInfo.getPage(),
                pageInfo.getSize()
        );
    }

    @Override
    public AppCheckRecord getById(String id) {
        return appCheckRecordService.selectByPrimaryKey(id);
    }

    @Async
    @Override
    public void save(EinvoiceDTO dto) {
        // png解析出xml
        AppCheckRecord record = XmlUtil.getConvert(dto.getPngBase64(), AppCheckRecord.class);
        BeanUtil.copyProperties(dto, record);
        // 判断是否有过记录
        if (notSave(record)) {
            record.setId(IDUtil.randomUUID());
            appCheckRecordService.insert(record);
        }
    }
}
